package com.knowswift.issues.mqtt;

import com.knowswift.issues.mqtt.message.MqttMessageHandler;
import com.knowswift.security.util.ApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MqttMessageHandlerContext {
    private final HashMap<String, MqttMessageHandler> map = new HashMap<>();
    private boolean init = true;
    private final ApplicationContextUtils applicationContextUtils;

    public MqttMessageHandlerContext(ApplicationContextUtils applicationContextUtils) {
        this.applicationContextUtils = applicationContextUtils;
    }

    public void handle(String topic, MqttMessage message) {
        if (init) {
            Map<String, MqttMessageHandler> beans = applicationContextUtils.getBeansWithInterFace(MqttMessageHandler.class);
            for (MqttMessageHandler value : beans.values()) {
                map.put(String.valueOf(value.supportMessageType()), value);
            }
            init = false;
        }
        String type = String.valueOf(message.getPayload()[1]);
        MqttMessageHandler mqttMessageHandler = map.get(type);
        if (mqttMessageHandler != null) {
            mqttMessageHandler.handleMessage(topic, message);
        } else {
            log.error("unknown message type {}", type);
        }
    }
}
